<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use App\Models\User;
use App\Models\Role;
use App\Models\Permission;


class AuthController extends Controller
{

    protected $token = 'api_token';//user表中token的name,用于标记token的类型，这里仅用作api,

    /**
     * @param Request $request
     * @return void
     */
    public function login(Request $request)
    {
        try {
            $request->validate([
                'name' => 'required',
                'password' => 'required'
            ]);
            $user = User::where('name', $request->name)->first();
            if (!$user || !Hash::check($request->password, $user->password)) {
                return response()->json([
                    'code' => 422,
                    'message' => '登录失败，请检查密码',
                ]);
            }
            $token = explode('|', $user->createToken($this->token)->plainTextToken);//16|XXXXXXXXXXXXXXXXXXXXXXXXXX

            // 指定角色的名称
            $targetRoleName = 'unity'; // 替换为实际的角色名
            // 获取指定角色的权限
            $targetRole = $user->roles()->where('name', $targetRoleName)->first();
            if ($targetRole) {
                $permissions = $targetRole->permissions()->select('meta', 'name')->where('parentId', '!=', 0)->get();
            } else {
                $permissions = []; // 如果角色不存在，则权限为空数组
            }

            return response()->json([
                'code' => 200,
                'data' => [
                    'token' => $token[1],
                    'userInfo' => [
                        'userId' => $user->id,
                        'userName' => $user->name,
                        'dashboard' => '0', // 假设是固定值
                        'role' => $user->roles->pluck('name')->toArray(), // 假设用户有一个 roles 关系
                        'permissions' => $permissions
                    ],
                ],
                'message' => '',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 422,
                'message' => '登录异常',
            ]);
        }
    }

    /**
     * @param Request $request
     * @return void
     */
    public function logout(Request $request)
    {
        return $request->user()->tokens()->delete();
        //return $request->user()->currentAccessToken()->delete();
    }

    /**
     * @param Request $request
     * @return void
     */
    public function test(Request $request)
    {
        $user = Auth()->user();
        //$user->assignRole(['writer', 'reader']);
        $user->assignRole([5,6]);
        //$user->syncRoles(['writer', 'reader2']);// 同步,删除以前的角色，然后把现有的角色加进去
        //$user->removeRole('writer');// 删除角色

//        $role = Role::where('name', 'reader')->where('guard_name', 'sanctum')->first();
//        $role->givePermissionTo(19);
//        $role->revokePermissionTo('edit articles');//角色删除权限
//        $role->syncPermissions(['edit articles', 'read2 articles']); // 同步权限

        return Auth()->user()->id;

    }

    /**
     * @param Request $request
     * @return void
     */
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'password' => 'required'
        ]);
        $existingUser = User::where(['name' => $request->name])->first();
        if ($existingUser) {
            return response()->json(['message' => '用户名已存在'], 409);
        }
        $user = User::create([
            'name' => $request->name,
            'password' => Hash::make($request->password),
            'dept' => [],
        ]);
        return Response()->json([
                'user_id' => $user->id,
                'access_token' => $user->createToken($this->token)->plainTextToken,
                'token_type' => 'Bearer'
        ]);
    }

}
